package com.yikaiye.android.yikaiye.ui.fragment;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.application.MyApplication;
import com.yikaiye.android.yikaiye.base.BaseFragment;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.FragmentIndexBinding;
import com.yikaiye.android.yikaiye.dialog.CallDialog;
import com.yikaiye.android.yikaiye.model.BannerModel;
import com.yikaiye.android.yikaiye.model.CustomerServiceModel;
import com.yikaiye.android.yikaiye.model.TypeProductModel;
import com.yikaiye.android.yikaiye.ui.activity.DesActivity;
import com.yikaiye.android.yikaiye.ui.activity.home.SearchActivity;
import com.yikaiye.android.yikaiye.ui.adapter.HomeTypeAdapter;
import com.yikaiye.android.yikaiye.ui.adapter.ProductAdapter;
import com.yikaiye.android.yikaiye.ui.fragment.viewmodel.IndexViewModel;
import com.yikaiye.android.yikaiye.utils.JumpIntent;
import com.yikaiye.android.yikaiye.utils.ToastHelper;
import com.yikaiye.android.yikaiye.utils.UMengUtil;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页
 */
public class IndexFragment extends BaseFragment<FragmentIndexBinding, IndexViewModel> {
    private List<TypeProductModel> typeData = new ArrayList<>();
    private ProductAdapter productAdapter;
    private HomeTypeAdapter homeTypeAdapter;

    @Override
    protected IndexViewModel bindModel() {
        return getViewModel(this, IndexViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    public void initData() {
        TypeProductModel typeProductModel = new TypeProductModel();
        for (int i = 0; i < 10; i++) {
            typeData.add(typeProductModel);
        }
        homeTypeAdapter = new HomeTypeAdapter(mContext, typeData);
        binding.typeRecyclerView.setAdapter(homeTypeAdapter);
        binding.hIndicator.bindRecyclerView(binding.typeRecyclerView);
        productAdapter = new ProductAdapter(mContext);
        binding.productRecyclerView.setAdapter(productAdapter);
        viewModel.getBanner();
        viewModel.getTypeList();
        viewModel.getProductList();
    }

    @Override
    protected void initClick() {
        // 轮播图
        viewModel.bannerData.observe(this, bannerModels -> binding.banner.setAdapter(new BannerImageAdapter<BannerModel>(bannerModels) {
                    @Override
                    public void onBindView(BannerImageHolder holder, BannerModel bannerModel, int position, int size) {
                        //图片加载自己实现
                        Glide.with(holder.itemView).load(bannerModel.getConsumerBannerUrl()).apply(RequestOptions.bitmapTransform(new RoundedCorners(30))).into(holder.imageView);
                    }
                }).addBannerLifecycleObserver(this) //添加生命周期观察者
                .setIndicator(new CircleIndicator(mContext)));

        // 专属客服返回数据
        viewModel.customerServiceData.observe(this, customerServiceModels -> {
            CallDialog callDialog = getCallDialog(customerServiceModels);
            if (!XXPermissions.isGrantedPermission(mContext, Permission.CALL_PHONE)) {
                XXPermissions.with(this).permission(Permission.CALL_PHONE).request((permissions, all) -> callDialog.showDialog());
            } else {
                callDialog.showDialog();
            }
            UMengUtil.setCountEventId(Constant.HOME_CONTACT_SERVICE);
        });

        // 产品分类返回数据
        viewModel.typeData.observe(this, typeProductModels -> {
            typeData = typeProductModels;
            binding.hIndicator.setVisibility(null == typeData || typeData.isEmpty() ? View.GONE : View.VISIBLE);
            homeTypeAdapter.onRefresh(typeData);
        });

        // 热门推荐返回数据
        viewModel.productData.observe(this, productModels -> productAdapter.submitList(productModels));

        // 搜索
        viewModel.onDelayClick(binding.llSearch, o -> {
            JumpIntent.jump(getActivity(), SearchActivity.class);
            UMengUtil.setCountEventId(Constant.HOME_CLICK_TO_SEARCH);
        });

        // 专属客服
        viewModel.onDelayClick(binding.ivCall, o -> viewModel.getCustomerService());

        viewModel.onDelayClick(binding.includeTabs.llQiMing, o -> {
            Bundle bundle = new Bundle();
            bundle.putString(Constant.NAME_KEY, mContext.getString(R.string.qi_ming));
            JumpIntent.jump(getActivity(), DesActivity.class, bundle);
            UMengUtil.setCountEventId(Constant.HOME_TOOL_NAME_COMPANY);
        });

        viewModel.onDelayClick(binding.includeTabs.llHeMing, o -> {
            if (binding.includeTabs.tvHeMing.getText().equals(mContext.getString(R.string.invoice))) {
                UMengUtil.setCountEventId(Constant.HOME_CLICK_BILL);
                if (!MyApplication.wxapi.isWXAppInstalled()) {
                    ToastHelper.show(mContext.getString(R.string.please_install_wechat));
                } else {
                    String appId = Constant.WE_CHAT_APP_ID; // 填移动应用(App)的 AppId，非小程序的 AppID
                    IWXAPI api = WXAPIFactory.createWXAPI(mContext, appId);
                    WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                    req.userName = "gh_47ef9f273ef9"; // 填小程序原始id
                    req.path = "pages/index/index?page=invoice"; // 拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                    req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
                    api.sendReq(req);
                }
            } else {
                Bundle bundle = new Bundle();
                bundle.putString(Constant.NAME_KEY, mContext.getString(R.string.he_ming));
                JumpIntent.jump(getActivity(), DesActivity.class, bundle);
                UMengUtil.setCountEventId(Constant.HOME_TOOL_VERIFY_COMPANY_NAME);
            }
        });

        binding.smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            viewModel.getBanner();
            viewModel.getTypeList();
            viewModel.getProductList();
            binding.smartRefreshLayout.finishRefresh(500);
        });
    }

    private @NonNull CallDialog getCallDialog(List<CustomerServiceModel> customerServiceModels) {
        CallDialog callDialog = new CallDialog(mContext);
        if (!customerServiceModels.isEmpty()) {
            if (customerServiceModels.size() == 1) {
                callDialog.setShowOne(customerServiceModels.get(0).getRealName(), customerServiceModels.get(0).getPhone());
            } else {
                callDialog.setShowTwo(customerServiceModels.get(0).getRealName(), customerServiceModels.get(0).getPhone(), customerServiceModels.get(1).getRealName(), customerServiceModels.get(1).getPhone());
            }
        }
        return callDialog;
    }
}
